/**
 *@描述：用户管理
 *@作者：顾云飞
 *@创建时间：2023/1/17
 *@最后修改时间：2023/1/18
 */
import {
  SaveOutlined,
  PlusOutlined,
  SearchOutlined,
  SyncOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
  ProForm,
  ProFormText,
  ProFormItem,
  ProFormSelect,
  ProFormRadio,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import {
  Row,
  Col,
  Space,
  Table,
  Popconfirm,
  Button,
  message,
  Modal,
  Card,
  Form,
  Input,
  Pagination,
  PaginationProps,
} from 'antd';
import { queryUserList, DeleteUserRequest } from '@/pages/Dashboard/System/User/service';
import { UserInfoSaveRequest } from '@/pages/Dashboard/System/User/service';
import { getSystemOfficeTreeData } from '@/pages/Dashboard/System/Office/service';
import { UserInfoSaveRequestParams, GetUserListRequestParams } from './data';
import { useRef, useState, useEffect } from 'react';
import type { ColumnsType } from 'antd/es/table';
import OfficeSelect from './OfficeSelect';
import styles from './style.less';
interface UserItem {
  id: string;
  nickName: string; // 真实姓名
  loginName: string;
  sex: string;
  officeName: string;
  mobile: string;
  email: number;
}

const UserList = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState([]); // 选择的树节点id
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState('1');
  const [total, setTotal] = useState('0');
  const [pageSize] = useState('5');
  const [keywords, setKeywords] = useState('');
  const [showUserModal, setShowUserModal] = useState<boolean>(false);
  const [userFormValues, setUserFormValues] = useState({});

  useEffect(() => {
    getUserList({
      pageNo: currentPage,
      pageSize: pageSize,
      keywords: keywords,
    });
  }, [selectedKeys, currentPage]);

  const columns: ColumnsType<UserItem> = [
    {
      title: '真实姓名',
      dataIndex: 'nickName',
      key: 'nickName',
      width: 160,
    },
    {
      title: '登录名',
      dataIndex: 'loginName',
      key: 'loginName',
      width: 160,
    },
    {
      title: '性别',
      dataIndex: 'sexLabel',
      key: 'sexLabel',
      width: 100,
    },
    {
      title: '部门',
      dataIndex: 'officeName',
      key: 'officeName',
      width: 120,
    },
    {
      title: '手机',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '操作',
      key: 'operation',
      width: 180,
      render: (_, record) => [
        <Button
          type="link"
          onClick={() => {
            setShowUserModal(true);
            setUserFormValues(record);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          title="确认删除吗？"
          okText="确定"
          cancelText="取消"
          onConfirm={() => delUser(record.id)}
        >
          <Button
            // className={styles.removeBtn}
            size="small"
            type="link"
            danger
          >
            删除
          </Button>
        </Popconfirm>,
        //    <a
        //    key="view"
        //    href={`/dashboard/system/user/details/${record.id}`}
        //  >
        //    查看
        //  </a>,
        <Button></Button>,
      ],
    },
  ];
  // 获取用户列表
  const getUserList = async ({
    pageNo,
    pageSize,
    keywords,
    officeId,
  }: {
    pageNo?: string;
    pageSize?: string;
    keywords?: string;
    officeId?: string;
  }) => {
    setLoading(true);
    const requestParams: GetUserListRequestParams = {
      pageNo: currentPage,
      pageSize: pageSize,
      keywords: keywords,
      officeId: selectedKeys && selectedKeys.length ? selectedKeys[0] : '',
    };
    // console.log(requestParams);
    const res = await queryUserList(requestParams);
    if (res.code == 200) {
      setData(res.data.list);
      setTotal(res.data.count);
      // formateList(res.data)
      // @ts-ignore
      // setTotal(res.data.total);
    }
    setLoading(false);
  };

  // 搜所
  const search = () => {
    getUserList({
      pageNo: currentPage,
      pageSize: pageSize,
      keywords: keywords,
      officeId: selectedKeys && selectedKeys.length ? selectedKeys[0] : '',
    });
  };
  //根据附件ID，删除用户，调用DeleteUserRequest接口
  //todo: 删除附件
  const delUser = async (id?: string) => {
    setLoading(true);
    const res = await DeleteUserRequest({
      ids: id,
    });
    if (res.code == 200) {
      setLoading(false);
      actionRef?.current?.reload();
      message.success('删除成功！');
    } else {
      setLoading(false);
      message.error('删除失败！');
    }
  };

  //分页-点击页码设置页码状态
  //todo: 分页，点击页码触发分页
  const onPageChange: PaginationProps['onChange'] = (page) => {
    setCurrentPage(page.toString());
  };

  // 输入框
  const onInputChange = (e: any) => {
    setKeywords(e.target.value);
  };
  // const editUser = async (id:string) => {
  //   setUserId(id);
  //   setShowUserModal(true)
  // }
  //添加人员成功触发的函数
  //todo: onSuccess
  const onSuccess = async () => {
    actionRef?.current?.reload();
  };
  const onCancel = () => {
    setShowUserModal(false);
    setUserFormValues({});
  };
  // 选择
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  return (
    <div>
      <Row gutter={20}>
        <Col span="4">
          <Card>
            <OfficeSelect setSelectedKeys={setSelectedKeys}></OfficeSelect>
          </Card>
        </Col>
        <Col span="20">
          <Card style={{ marginBottom: '20px' }}>
            <Form layout="inline">
              <Form.Item label="关键字">
                <Input placeholder="请输入" onChange={onInputChange} onPressEnter={search} />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} onClick={search}>
                    搜索
                  </Button>
                  <Button type="default" icon={<SyncOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
          <Card
            title={
              <Space>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setShowUserModal(true);
                  }}
                >
                  新增
                </Button>

                <Button
                  type="primary"
                  icon={<DeleteOutlined />}
                  danger
                  disabled={selectedRowKeys.length === 0}
                  onClick={() => {
                    delUser(selectedRowKeys.toString());
                  }}
                >
                  批量删除
                </Button>
              </Space>
            }
          >
            <Table
              style={{ marginBottom: '20px' }}
              columns={columns}
              rowSelection={{
                // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                selectedRowKeys,
                onChange: onSelectChange,
              }}
              dataSource={data}
              // request ={ async (
              //   params: {
              //     pageSize:number;
              //     current:number;
              //   },
              // sort, filter) => {
              //   console.log(params)
              //    const res = await queryUserList({
              //       pageNo: params.current,
              //       pageSize:params.pageSize,
              //       officeId:''
              //    });
              //    return {
              //      data: res.data.list,
              //      total:res.data.count
              //    }
              // }}
              rowKey="id"
              // tableAlertOptionRender={() => {
              //   return (
              //     <Space size={16}>
              //       <Button type="primary" icon={<PlusOutlined />} onClick={() => setShowUserModal(true)}>新增用户</Button>
              //       <Popconfirm
              //       title="确认删除吗？"
              //       okText="确定"
              //       cancelText="取消"
              //       onConfirm={() => {
              //         delUser(selectedRowKeys.toString())
              //       }}
              //   >
              //       <Button
              //           // className={styles.removeBtn}
              //           type="link"
              //           danger
              //       >批量删除</Button>
              //   </Popconfirm>,
              //       {/* <a>导出数据</a> */}
              //     </Space>
              //   );
              // }}
              // scroll={{ y: 250 }}
              pagination={false}
              size="small"
            />
            <Pagination
              showTotal={(total) => `共 ${total} 条数据`}
              showQuickJumper
              current={Number(currentPage) || 1}
              pageSize={Number(pageSize) || 5}
              total={Number(total) || 0}
              onChange={onPageChange}
            />
          </Card>
          {(userFormValues && Object.keys(userFormValues).length) || showUserModal ? (
            <UserFormModal
              propOfficeId={selectedKeys[0]}
              userFormValues={userFormValues}
              onSuccess={onSuccess}
              show={showUserModal}
              onCancel={onCancel}
            ></UserFormModal>
          ) : null}
        </Col>
      </Row>
    </div>
  );
};
// 添加用户表单
const AddUserForm = ({
  propsOfficeId,
  userFormValues,
  onCancel,
  onSuccess,
}: {
  propsOfficeId?: string;
  userFormValues?: any;
  onCancel?: () => void;
  onSuccess?: () => void;
}) => {
  const [loading, setLoading] = useState(false);
  const formRef = useRef<ProFormInstance>();

  const handleSubmit = (e: any) => {
    formRef.current?.validateFieldsReturnFormatValue?.().then((val) => {
      setLoading(true);
      const requestParams: UserInfoSaveRequestParams = {
        ...val,
        id: userFormValues?.id,
      };
      UserInfoSaveRequest(requestParams).then((res) => {
        if (res.code == 200) {
          setLoading(false);
          onSuccess?.();
          onCancel?.();
        } else {
          setLoading(false);
        }
      });
    });
  };
  return (
    <ProForm
      initialValues={userFormValues}
      formRef={formRef}
      layout="horizontal"
      className={styles.form}
      labelCol={{
        style: {
          width: 80,
        },
      }}
      submitter={false}
    >
      <ProFormText
        name="loginName"
        label="用户名"
        required
        rules={[
          {
            required: true,
            message: '请输入用户名',
          },
        ]}
      ></ProFormText>
      <ProFormText
        name="nickName"
        label="用户昵称"
        required
        rules={[
          {
            required: true,
            message: '请输入用户昵称',
          },
        ]}
      ></ProFormText>
      <ProFormTreeSelect
        name="officeId"
        label="部门"
        initialValue={propsOfficeId}
        fieldProps={{
          defaultValue: propsOfficeId,
        }}
        placeholder="请选择"
        allowClear
        required
        rules={[
          {
            required: true,
            message: '请选择部门',
          },
        ]}
        request={async () => {
          const res = await getSystemOfficeTreeData();
          return res.data;
        }}
      />
      <ProFormText name="mobile" label="手机号码"></ProFormText>
      <ProFormText name="email" label="邮箱"></ProFormText>
      <ProFormRadio.Group
        label="状态"
        name="loginFlag"
        options={[
          {
            label: '正常',
            value: '1',
          },
          {
            label: '禁用',
            value: '0',
          },
        ]}
      />
      <ProFormSelect
        name="sex"
        label="用户性别"
        options={[
          {
            value: '0',
            label: '男',
          },
          {
            value: '1',
            label: '女',
          },
        ]}
      ></ProFormSelect>
      <ProFormSelect
        name="roleId"
        label="角色"
        options={[
          {
            label: '角色1',
            value: '1',
          },
          {
            label: '角色2',
            value: '2',
          },
        ]}
        required
        rules={[
          {
            required: true,
            message: '请选择角色',
          },
        ]}
      ></ProFormSelect>
      <ProFormItem>
        <Button
          size="large"
          type="primary"
          onClick={handleSubmit}
          icon={<SaveOutlined />}
          style={{ marginLeft: 80 }}
        >
          确定
        </Button>
      </ProFormItem>
    </ProForm>
  );
};
// 弹窗
const UserFormModal = ({
  propOfficeId,
  userFormValues,
  show,
  onCancel,
  userId,
  onSuccess,
}: {
  propOfficeId: string;
  userFormValues: any;
  show: boolean;
  onCancel?: () => void;
  userId?: string;
  onSuccess?: () => void;
}) => {
  return (
    <Modal
      title={<Space>{Object.keys(userFormValues).length > 0 ? '修改用户' : '添加用户'}</Space>}
      visible={show}
      width={'40%'}
      centered
      destroyOnClose={true}
      footer={false}
      bodyStyle={{ padding: 20 }}
      onCancel={onCancel}
    >
      <AddUserForm
        propsOfficeId={propOfficeId}
        userFormValues={userFormValues}
        onCancel={onCancel}
        onSuccess={onSuccess}
      />
    </Modal>
  );
};

export default UserList;
